#_*_ coding:UTF-8 _*_
__author__ = 'shaowei'


import os
# import sys
import shutil
import pyNotificationCenter
import CommandInteraction
import HandleXcodeBuild
import commands


#设置默认路径

default_work_path = "~/Git/PushPrompt"  # 默认的project根目录
destination_path = "~/website/installapp/public/com.AISpeech.PushPrompt"  # 最终打包的ipa文件的存放处

destination_path = os.path.expanduser(destination_path)

work_path = CommandInteraction.get_project_path(default_work_path)

#切换到工作目录
work_path = os.path.expanduser(work_path)
os.chdir(work_path)

params = HandleXcodeBuild.get_build_settings()  # 获取 项目预设参数列表

# .app 文件路径
# app_path = os.path.join(params["BUILT_PRODUCTS_DIR"], params["WRAPPER_NAME"])
configuration = CommandInteraction.get_build_configuration()  # 获取 编译配置

app_folder_path = os.path.join(params["SRCROOT"], "build", configuration + params["EFFECTIVE_PLATFORM_NAME"])
app_path = os.path.join(app_folder_path, params["WRAPPER_NAME"])
dsym_path = os.path.join(app_folder_path, params["DWARF_DSYM_FILE_NAME"])
dsym_filename = params["DWARF_DSYM_FILE_NAME"]
ipa_name = params["PRODUCT_NAME"] + ".ipa"
ipa_path = os.path.join(destination_path, ipa_name)

# xcodebuild -sdk iphoneos -project 'PushPrompt.xcodeproj' -scheme 'PushPrompt' -configuration 'Release' clean build
commands_xcode_build = "xcodebuild "
commands_xcode_build = commands_xcode_build + " -sdk " + "iphoneos"
commands_xcode_build = commands_xcode_build + " -configuration " + configuration
# commands_xcode_build = commands_xcode_build + " DEPLOYMENT_LOCATION=YES "
commands_xcode_build += " clean build "

print "\ncommands_xcode_build:", commands_xcode_build, "\n"

status, shell_output = commands.getstatusoutput(commands_xcode_build)
print "status:", status, "\nshell_out:", shell_output

# xcrun -sdk iphoneos PackageApplication -v "$app_path" -o "$ipa_path" --embed "#{options.embed || @dsym_path}"
commands_xcrun = "xcrun"
commands_xcrun = commands_xcrun + " -sdk " + "iphoneos"
commands_xcrun += " PackageApplication "
commands_xcrun = commands_xcrun + " -v " + " '%s' " % app_path
commands_xcrun = commands_xcrun + " -o " + " '%s' " % ipa_path
# commands_xcrun = commands_xcrun + " --embed " + " '%s' " % dsym_path

print "\ncommands_xcrun:", commands_xcrun, "\n"

status, shell_output = commands.getstatusoutput(commands_xcrun)
print "status:", status, "\nshell_out:", shell_output

print "\n*******All Build Finish!********\n"

# 清除中间文件
path_build = os.path.join(work_path, "build")
if os.path.isdir(path_build):
	shutil.rmtree(path_build, True)
	print "-----已经清除临时文件夹：", path_build
else:
	print "-----没有 临时文件夹"

print "\n"

notify_title = u"项目：%s 编译完成." % params["PRODUCT_NAME"]
notify_content = u"project:%s;\n destination：%s" % (params["SRCROOT"], ipa_path )

pyNotificationCenter.notify(notify_title, None, notify_content, sound=True )